<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Section extends Model {
	
	protected $guarded = array('id');
	
	public function book() {
		return $this->belongsTo('App\Models\Book');
	}
	
	public function comments() {
		return $this->hasMany('App\Models\Comment')->orderBy('id', 'DESC');
	}
	
	public function preSection($backend = false) {
		return $this->getSectionIdByorder($this->order-1, $backend);
	}
	
	public function nextSection($backend = false) {
		return $this->getSectionIdByorder($this->order+1, $backend);
	}
	
	private function getSectionIdByorder($order, $backend) {
		$section = Section::where('book_id', $this->book_id)
			->where('order', $order)
			->first();
		if($backend) {
			return $section ? $section->id : '';
		}else {
			return $section ? $section->order : '';
		}
	}
	
	public static $rules = [
		'book_id' => 'required',
		'name' => 'required',
		'content' => 'required',
		'order' => 'required',
	];
	
	public static $msgs = [
		'book_id.required' => '书籍ID不能为空',
		'name.required' => '章节名称不能为空',
		'content.required' => '章节内容不能为空',
		'order.required' => '章节顺序不能为空'
	];
}
